import 'package:get/get.dart';
import 'package:sinosheets/mixin/refresh_mixin.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/utils/bus_utils.dart';
import 'package:sinosheets/utils/lottie_utils.dart';

class CategoryLogic extends GetxController with RefreshMixin {
  int selectedIndex = 0;
  List<dynamic> categoryList = [];

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    LottieUtils.showToastLoading();
    onRefresh();
    bus.on('network_refresh', (value) {
      onRefresh();
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  @override
  Future<void> onRefresh() async {
    await getCategory();
    super.onRefresh();
  }

  /// 获取分类
  List<dynamic> leftList = [];
  List<dynamic> rightList = [];
  Future<void> getCategory() async {
    BaseResponse response = await ProductApi.getCategory();
    if (response.isSuccess) {
      categoryList = response.data ?? [];
      leftList = categoryList;
      for (var category in leftList) {
        // 默认值
        String nameEN = '';
        if (category['nameList'] is List) {
          final enItem = (category['nameList'] as List).firstWhere((e) => e['lang'] == 'en', orElse: () => null);
          if (enItem != null && enItem['content'] != null) {
            nameEN = enItem['content'];
          }
        }
        category['nameEN'] = nameEN;
      }
      rightList = (categoryList[selectedIndex]['children'] ?? []) as List;
      for (var category in rightList) {
        // 默认值
        String nameEN = '';
        if (category['nameList'] is List) {
          final enItem = (category['nameList'] as List).firstWhere((e) => e['lang'] == 'en', orElse: () => null);
          if (enItem != null && enItem['content'] != null) {
            nameEN = enItem['content'];
          }
        }
        category['nameEN'] = nameEN;
      }
    }
    LottieUtils.hideToastLoading();
    update();
  }

  Future<void> getCategoryList(int index) async {
    rightList = (categoryList[index]['children'] ?? []) as List;
    for (var category in rightList) {
      // 默认值
      String nameEN = '';
      if (category['nameList'] is List) {
        final enItem = (category['nameList'] as List).firstWhere((e) => e['lang'] == 'en', orElse: () => null);
        if (enItem != null && enItem['content'] != null) {
          nameEN = enItem['content'];
        }
      }
      category['nameEN'] = nameEN;
    }
    update();
  }
}
